package com.climber.android.commonres.widget.indicator

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import com.climber.android.commonres.R
import io.library.android.indicator.IndicatorViewPager

abstract class AbstractPagerTabTemplateAdapter(val context: Context,
                                               val fragments: List<Fragment>,
                                               val titleArray: List<String>,
                                               fragmentManager: FragmentManager) : IndicatorViewPager.IndicatorFragmentPagerAdapter(fragmentManager)  {
    private val layoutInflater = LayoutInflater.from(context)

    //the textView's LayoutParams is LinearLayout.LayoutParams
    abstract fun changeTextViewStyle(textView : TextView, position : Int)

    override fun getViewForTab(position: Int, view: View?, container: ViewGroup?): View {
        var convertView = view
        if (convertView == null) {
            convertView = layoutInflater.inflate(R.layout.com_view_abstract_pager_tab, container, false)
        }

        val textView = convertView as TextView
        textView.text = getPageTitle(position)
        changeTextViewStyle(textView, position)

        return convertView
    }

    override fun getFragmentForPage(position: Int): Fragment = fragments[position]

    override fun getCount(): Int = fragments.size

    protected fun getTextWidth(textView: TextView?): Int {
        if (textView == null) {
            return 0
        }
        val text = textView.text.toString()
        val paint = textView.paint
        return paint.measureText(text, 0, text.length).toInt()
    }

    private fun getPageTitle(position: Int): CharSequence = titleArray[position]
}